import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    api_key=os.getenv("DASHSCOPE_APIKEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    model="qwen-max",
)

# 使用大模型进行基础对话

# response = llm.invoke("你好")
# print(response)


from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

# 链式调用
prompt = ChatPromptTemplate.from_messages([("human", "{city}天气如何"),
                                           ])

chain = prompt | llm | StrOutputParser()

# response = chain.invoke({"city": "北京"})
#
# print(response)

# 基于langchain的function calling

from langchain_core.tools import tool


@tool
def count_emails(last_days: int) -> int:
    """返回前几天有几封邮件"""
    return last_days * 10


tools = [count_emails]
llm_with_tools = llm.bind_tools(tools)
# res = llm_with_tools.invoke("最近5天发送了几封邮件")
# print(res)

# 基于langchain构建智能体

from langchain.agents import initialize_agent
from langchain.agents import AgentType
from baidusearch.baidusearch import search


@tool
def web_search(query: str) -> str:
    """
    当需要进行网络资料搜索的时候可以使用该用具，返回搜索的结果
    """

    return search(query, 3)


@tool
def file_saver(content: str, filename: str) -> str:
    """
    当需要写入文件的时候，可以使用该工具
    Args:
        content: 需要写入的文件内容
        filename: 文件名称
    """
    with open(filename, "w", encoding="utf-8") as f:
        f.write(content)
    return "文件写入成功"


tools.append(web_search)
tools.append(file_saver)
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,

)

# agent.invoke("请从网络中查找dify有哪些功能列表写到本地文件")

# 基于Langgraph来开发智能体
from langgraph.prebuilt import create_react_agent

graph_agent = create_react_agent(llm, tools=tools)
prompt = ChatPromptTemplate.from_messages([

    ("human", "{input}")

]).invoke({"input","请从网络中查找dify有哪些功能列表写到本地文件"})
ret = graph_agent.invoke(prompt)
